package com.ying.myrabbitmq.amqp;

import com.rabbitmq.client.Channel;
import com.ying.myrabbitmq.user.Student;
import com.ying.myrabbitmq.user.User;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = {"ying.queue"})
public class RabbtiMqDirect {

    /**
     * @param message 消息
     * @param user    对象内容
     * @param channel 通道
     * @RabbitListener(queues = {"ying.queue"}) 绑定的队列名字
     * @RabbitHandler 可以按照对象类型来接收不同的消息
     */


    @RabbitHandler
    public void receive1(Message message, User user, Channel channel) {
        System.out.println("receive1只接受User对象传来的消息------>");
        System.out.println("通道信息------>" + channel);
        System.out.println("user信息------>" + user);
        System.out.println("接收到消息--->" + message.getBody());

        //channel内顺序自增
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {

            /**
             *  手动签收
             *  basicAck(long deliveryTag, boolean multiple)
             *  deliveryTag     第几个货物
             *  multiple        是否批量签收
             */

            channel.basicAck(deliveryTag, false);
            System.out.println("签收第" + deliveryTag + "货物");

            /**
             *  退签
             *  basicNack(long deliveryTag, boolean multiple, boolean requeue)
             *  deliveryTag     第几个货物
             *  multiple        是否批量签收
             *  requeue         是否重新投递到MQ消息队列里, 不投递直接丢弃消息
             */

            channel.basicNack(deliveryTag, false, true);
        } catch (Exception e) {
            //失败肯定是网络原因
            e.printStackTrace();
        }
    }

    @RabbitHandler
    public void receive2(Student student) {
        System.out.println("receive2只接受student对象传来的消息------>");
        System.out.println("student信息------>" + student);
    }

}
